package file;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**
 * http://blog.csdn.net/jeanszu/article/details/8966093
 * 下载控制器，由这里接收下载的任务，并进行分发并启动各个子线程
 * 同时创建最终保存文件
 * USER: lintc 【lintiancong@zhuojianchina.com】
 * DATE: 2017-05-16 16:39
 */
public class DownLoadManager {

    private int threadNum = 8;

    private String downloadUrl;//下载的url地址

    public DownLoadManager(String downloadUrl) {
        super();
        this.downloadUrl = downloadUrl;
    }

    public void startDownload(){
        try {
            //创建下载的url和保存文件
            URL url = new URL(downloadUrl);
            URLConnection connection = url.openConnection();
            int contentLength = connection.getContentLength();
            System.out.println("Download content length is: " + contentLength);
            File file = new File("C:\\Users\\ucmed\\Desktop\\1.log");
            System.out.println("file path is: " + file.getAbsolutePath());

            //分割下载任务，启动下载线程
            long sublen = contentLength/threadNum;
            for(int i = 0; i < threadNum; i++) {
                long starPos = sublen * i;
                long endPos = sublen * (i + 1) - 1;
                DownloadThread thread = new DownloadThread(starPos, endPos, file, url);
                thread.start();
            }
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String url = "http://app.hzwsjsw.gov.cn/zjkj-syslog/default.log.2017-05-14";
        DownLoadManager manager = new DownLoadManager(url);
        manager.startDownload();
    }
}
